<template>
  <div class="w100">
    <el-upload
      :action="action"
      accept="image/*"
      :before-remove="beforeRemove"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :data="getReqData"
      :on-error="handleError"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :show-file-list="false"
    >
      <el-button
        icon="ele-Search"
        :loading="loading"
        type="primary"
      >
        {{ $t("formgen.ocr.identifyingText") }}
      </el-button>
      <template #tip>
        <div class="el-upload__tip">{{ $t("formgen.ocr.tips") }}</div>
      </template>
    </el-upload>
  </div>
</template>

<script setup lang="ts" name="TOcr">
import { baseUrl } from "@/utils/auth";
import { i18n } from "@/i18n";
import { computed, defineProps, inject, ref } from "vue";
import { ElMessage } from "element-plus";
import { formItemProps } from "@/views/formgen/components/FormItem/hooks/useFormItemHook";
import { ReturnTypeOfUseUserForm } from "@/views/formgen/components/GenerateForm/hooks/useUserForm";
import { USER_FORM_STATE_KEY } from "@/views/formgen/components/GenerateForm/types/constants";

const props = defineProps({
  ...formItemProps
});

const fileList = ref<File[]>([]);
const action = ref(baseUrl + "/form/common/ocr");
const loading = ref(false);

const getReqData = computed(() => {
  return {
    type: props.item?.ocrType,
    options: props.item?.options || {}
  };
});

const handleRemove = (file: File, fileList: File[]) => {
  console.log(file, fileList);
};

const handlePreview = (file: File) => {
  console.log(file);
};

const handleExceed = () => {
  // Handle exceeding upload limit (if applicable)
};

const beforeRemove = () => {
  // Handle confirmation before removal (if applicable)
};

const userFormStore = inject<ReturnTypeOfUseUserForm>(USER_FORM_STATE_KEY);

const handleSuccess = (res: any) => {
  loading.value = false;
  ElMessage.success(i18n.global.t("formI18n.all.success"));

  if (!Object.keys(props.item?.fieldMapping).length) {
    ElMessage.error(i18n.global.t("formgen.ocr.errorMapping"));
    return;
  }
  if (res.data && userFormStore) {
    const { currentPageConfig, fieldIdIndex } = userFormStore;
    Object.keys(res.data).forEach(key => {
      const modelKey = props.item?.fieldMapping[key];
      if (fieldIdIndex.value[modelKey] > -1) {
        userFormStore!.setFormModelItem(modelKey, res.data[key]);
        // 判斷字符串以什麽開頭
        // 如果是圖片要强制刷新下組件
        if (modelKey.startsWith("image")) {
          // 找到這個組件 修改
          const list = currentPageConfig.value?.fields.filter(item => item.vModel === modelKey) as any[];
          if (list && list.length) {
            list[0]["key"] = new Date().getTime();
          }
        }
      }
    });
  }
};

const handleError = (err: any) => {
  ElMessage.error(err);
  loading.value = false;
};

const handleBeforeUpload = () => {
  loading.value = true;
};
</script>
